package org.pyframe.parser;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

@SuppressWarnings("rawtypes")
public class XMLParser {
	public Document doc;
	
	private XMLParser() {
	}
	
	public static XMLParser create(String xml) throws Exception {
		XMLParser xp = new XMLParser();
		xp.load(xml);
		return xp;
	}
	
	public static XMLParser create(InputStream is) throws Exception {
		XMLParser xp = new XMLParser();
		xp.load(is);
		return xp;
	}
	
	void load(String xml) throws Exception {
		SAXBuilder builder = new SAXBuilder();
		this.doc = builder.build(new FileInputStream(xml));
	}
	
	void load(InputStream is) throws Exception {
		SAXBuilder builder = new SAXBuilder();
		this.doc = builder.build(is);
	}

	public Element getTele() {
		return doc.getRootElement();
	}
	
	public Packet createPacket(String id) throws Exception {
		Packet p = new Packet();
		List items = XPath.newInstance("/tele/packet[@id=\""+id+"\"]/item").selectNodes(doc);
		for(int i=0; i<items.size(); i++) {
			Element element = (Element) items.get(i);
			Part part = new Part();
			part.setName(element.getText());
			part.setType(element.getAttributeValue("type"));
			
			String length = element.getAttributeValue("length");
			if(length!=null) {
				part.setLength(Integer.parseInt(element.getAttributeValue("length")));
			}
			String defaultValue = element.getAttributeValue("default");
			if (!"".equals(defaultValue)) {
				part.setValue(defaultValue);
			}
			p.addPart(part);
		}
		return p;
	}
}
